package com.zhike.service.im.manager;

import java.util.Date;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.zhike.common.dto.MsgBody4Group;
import com.zhike.common.enums.ResultCode;
import com.zhike.common.enums.YesNoEnum;
import com.zhike.common.exception.ZkimException;
import com.zhike.common.repository.HistoryMessage;
import com.zhike.component.BeanAccessor;
import com.zhike.service.messages.IChatSessionService;
import com.zhike.service.messages.impl.HistoryMessageRepository;

import cn.hutool.core.util.IdUtil;
import lombok.extern.slf4j.Slf4j;
import net.x52im.mobileimsdk.server.protocal.Protocal;

@Slf4j
public abstract class StorageMessage {

    public abstract String getSessionId();

    // 消息存储
    public Boolean store(String groupId, String groupName, MsgBody4Group root) {
        String sessionId = getSessionId();
        if (StringUtils.isBlank(sessionId)) {
            log.warn("会话Id是空,存储不再继续 群ID:{}", groupId);
            return false;
        }

        try {
            HistoryMessage historyMessage = new HistoryMessage();
            historyMessage.setId(IdUtil.getSnowflakeNextIdStr());
            historyMessage.setSessionId(sessionId);
            historyMessage.setGroupId(groupId);
            historyMessage.setChatType(root.getCy());
            historyMessage.setMsgType(root.getTy());
            historyMessage.setContent(root.getM());
            historyMessage.setFp(Protocal.genFingerPrint());
            historyMessage.setDeleted(YesNoEnum.NO.getValue());
            historyMessage.setRevoked(YesNoEnum.NO.getValue());
            historyMessage.setTimestamp(new Date());

            HistoryMessageRepository historyMessageRepository = BeanAccessor.getBean(HistoryMessageRepository.class);
            historyMessageRepository.addHistoryMessage(historyMessage);

            IChatSessionService chatSessionService = BeanAccessor.getBean(IChatSessionService.class);
            chatSessionService.updateGroupSession(historyMessage, groupName, "");
        } catch (Exception e) {
            e.printStackTrace();
            throw new ZkimException(ResultCode.DB_ERROR);
        }

        return Boolean.TRUE;

    }
}
